<?php
class Upload {
	//允许大小
	private $size;
	private $type;
	public $error;
	public function __construct($size = NULL, $type = NULL) {
		$this -> size = is_null($size) ? 2000000 : $size;
		$this -> type = is_null($type) ? array('jpg', 'png', 'jpeg', 'gif') : $type;
	}

	public function up() {
		//1.重组数组（为了以后更好的循环操作）
		$arr = $this -> resetArr();
		p($arr);
		//2.筛选
		foreach ($arr as $v) {
			if (!$this -> filter($v)) {
				//空数组也是假
				return array();
			}
		}
		//3.上传
		$destArr = array();
		foreach ($arr as $v) {
			//上传完毕之后把完整路径压入空数组
			$destArr[] = $this -> move($v);
		}
		return $destArr;
	}

	//移动上传方法
	private function move($v) {
		//目录
		$path = './Upload/' . date('ymd');
		is_dir($path) || mkdir($path, 0777, true);
		//文件名
		$type = strrchr($v['name'], '.');
		$fileName = time() . mt_rand(0, 99999) . $type;
		//完整的目标
		$dest = $path . '/' . $fileName;
		move_uploaded_file($v['tmp_name'], $dest);
		return $dest;
	}

	//筛选方法，需要返回true或者是false
	private function filter($v) {
		//获得所传文件的类型了
		$type = ltrim(strrchr($v['name'], '.'), '.');
		switch (true) {
			//1.判断文件是否上传
			case $v['error'] == 4 :
				$this -> error = '没有文件被上传';
				return false;
			//2.是否是合法的上传文件
			case !is_uploaded_file($v['tmp_name']) :
				$this -> error = '不是一个合法的上传文件';
				return false;
			//3.判断大小是否允许
			case $v['size'] > $this->size :
				$this -> error = '文件超过配置大小';
				return false;
			//4.类型是否允许
			case !in_array($type, $this->type) :
				$this -> error = '上传文件类型不允许';
				return false;
			//判断上传的3种error错误

			default :
				return true;
		}

	}

	//	Array
	//(
	//  [0] => Array
	//      (
	//          [name] => shanghai.jpg
	//          [type] => image/jpeg
	//          [tmp_name] => /Applications/MAMP/tmp/php/phpPEAjqZ
	//          [error] => 0
	//          [size] => 191415
	//      )
	//  [1] => Array
	//      (
	//          [name] => shanghai.jpg
	//          [type] => image/jpeg
	//          [tmp_name] => /Applications/MAMP/tmp/php/phpPEAjqZ
	//          [error] => 0
	//          [size] => 191415
	//      )
	//
	//)
	private function resetArr() {
		$arr = array();
		foreach ($_FILES as $v) {
			if (is_array($v['name'])) {
				foreach ($v['name'] as $key => $value) {
					$arr[] = array(
					'name' => $value, 
					'type' => $v['type'][$key], 
					'tmp_name' => $v['tmp_name'][$key], 
					'error' => $v['error'][$key], 
					'size' => $v['size'][$key], 
					);
				}
			} else {//单文件
				$arr[] = $v;
			}
		}
		return $arr;
	}

}
?>